package com.atzxh.heima.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author 小红同学
 * @date 2023-12-17-21:10
 * @description
 */
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug("{}",byteBuf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                })
                .connect("localhost", 8088);

        // 1、使用sync异步处理
//        channelFuture.sync();
//        Channel channel = channelFuture.channel();
//        log.debug("{}",channel);
//        channel.writeAndFlush("hello");

        // 2、使用 addListener(回调对象)方法异步处理结果
//        channelFuture.addListener(new ChannelFutureListener() {
//            @Override
//            public void operationComplete(ChannelFuture channelFuture) throws Exception {
//                // 此时代码会在nio线程执行
//                Channel channel = channelFuture.channel();
//                log.debug("{}",channel);
//                channel.writeAndFlush("hello");
//            }
//        });
        Channel channel = channelFuture.sync().channel();
        log.debug("{}",channel);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String s = scanner.nextLine();
                if ("q".equals(s)) {
                    channel.close();
                    scanner.close();
                    // 不能在这里处理关闭之后的操作
//                    log.debug("处理关闭之后的操作");
                    break;
                }
                channel.writeAndFlush(s);
            }
        },"input").start();

        // 获取closeFuture对象  1）同步处理关闭    2）异步处理
        ChannelFuture closeFuture = channel.closeFuture();
        // 同步
//        log.debug("等待关闭中。。。。");
//        closeFuture.sync();
//        log.debug("处理关闭之后的操作");

        // 异步
        closeFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            log.debug("处理关闭之后的操作");
            // 优雅停机
            group.shutdownGracefully();
        });
    }
}
